#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include  "common.h"

// 函数：去除字符串中的空格
static char *removeSpacesFromConstString(const char *str) {
    if (str == NULL) return NULL; // 检查空指针

    // 计算去掉空格后的字符串长度
    size_t len = 0;
    for (size_t i = 0; str[i] != '\0'; i++) {
        if (!isspace((unsigned char)str[i])) {
            len++;
        }
    }

    // 分配内存存储新字符串（包括终止符）
    char *result = (char *)malloc(len + 1);
    if (result == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return NULL;
    }

    // 复制非空格字符到新字符串
    size_t j = 0;
    for (size_t i = 0; str[i] != '\0'; i++) {
        if (!isspace((unsigned char)str[i])) {
            result[j++] = str[i];
        }
    }
    result[j] = '\0'; // 添加终止符

    return result;
}

// 函数：以十六进制打印结构体的内存内容
void print_hex_string(const void *data, size_t size, char *hex_string, size_t hex_string_size) 
{
    static const char hex_digits[] = "0123456789abcdef";
    char *p = hex_string;
    const U8 *byte_data = (const U8 *)data;
 
    for (size_t i = 0; i < size; ++i) {
        *p++ = hex_digits[byte_data[i] >> 4];
        *p++ = hex_digits[byte_data[i] & 0x0F];
    }
    *p = '\0';
}

// 从16进制字符串还原内存内容
int parse_hex_string(const char *hex_string, void *data, size_t size) {
    static const char hex_digits[] = "0123456789abcdefABCDEF";
    const char *p = removeSpacesFromConstString(hex_string);
    U8 *byte_data = (U8 *)data;
 
    for (size_t i = 0; i < size; ++i) {
        char c1 = *p++;
        char c2 = *p++;
 
        if (c1 == '\0' || c2 == '\0' || strchr(hex_digits, c1) == NULL || strchr(hex_digits, c2) == NULL) {
            return -1; // 错误：字符串长度不足或包含无效字符
        }
 
        byte_data[i] = (strchr(hex_digits, c1) - strchr(hex_digits, '0')) << 4 |
                       (strchr(hex_digits, c2) - strchr(hex_digits, '0'));
    }
    return 0;
}

char devName[2048] = {};

int getEp(char *devName)
{
    return 0;
}

BaseInfo_t cxlBaseInfo = {};

void fillBaseInfo(const char* name, const char* value)
{
    if (strcmp(name, "devName") == 0) {
        strncpy(devName, value, sizeof(devName));
    } else if (strcmp(name, "port") == 0) {
        cxlBaseInfo.port = atoi(value);
    } else if (strcmp(name, "ld") == 0) {
        cxlBaseInfo.ld = atoi(value);
    } else if (strcmp(name, "level") == 0) {
        cxlBaseInfo.level = atoi(value);
    }
}

int func1(int a, BaseInfo_t *bt, Section1Data *section1Data) {
    printf("this is func1 \n");
    printf("this is func1 param1 : %s \n", section1Data->key1);
    printf("this is func1 param2 : %d \n", section1Data->key2);
    return 1;
}

int func2(int a, BaseInfo_t *bt, Section2Data *section2Data) {
    printf("this is func2 \n");
    printf("this is func2 param1 : %s \n", section2Data->key4);
    printf("this is func2 param2 : %s \n", section2Data->key5);
    printf("this is func2 param3 : %d \n", section2Data->key6);
    return 2;
}

